package org.fastsyncer.rest.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.util.ApplicationUtil;

public class WebServiceInterceptor extends AbstractPhaseInterceptor<Message> {

    public WebServiceInterceptor() {
        super(Phase.RECEIVE);
    }

    public void handleMessage(Message message) throws Fault {
        // 指定CXF获取客户端的HttpServletRequest : http-request；
        HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        String ipAddress = "";
        if (null != request) {
            // 取客户端IP地址
            ipAddress = getUserIpAddr(request);

            // 允许本机访问
            if (ipAddress.equals(ApplicationUtil.getKey(CommonConstant.SERVER_IP))) {
                return;
            }
            // 允许来自白名单访问
            String ips = ApplicationUtil.getKey(CommonConstant.REST_APPROVAL_IP);
            String[] split = StringUtils.split(ips, "|");
            if (null != split && split.length > 0) {
                for (String ip : split) {
                    if ("".equals(ip)) {
                        continue;
                    }

                    if (ipAddress.equals(ip)) {
                        return;
                    }
                }
            }
        }
        String err = "IP address " + ipAddress + " is forbidden!";
        throw new Fault(new IllegalAccessException(err));
    }

    /**
     * 获取IP地址的方法
     * 
     * @param request
     * @return
     */
    private String getUserIpAddr(HttpServletRequest request) {
        // 获取经过代理的客户端的IP地址; 排除了request.getRemoteAddr() 方法
        // 在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了
        String ip = request.getHeader("x-forwarded-for");
        // 屏蔽以下获取方式：利用安全工具扫描时,检测存在漏洞
        //		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        //			ip = request.getHeader("Proxy-Client-IP");
        //		}
        //		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        //			ip = request.getHeader("WL-Proxy-Client-IP");
        //		}
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.indexOf(",") > 0) {
            String[] arr = ip.split(",");
            // 有多个ip时取最后一个ip
            ip = arr[arr.length - 1].trim();
        }
        return ip;
    }

}